package com.kl.seq;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.LockSupport;

/**
 * 确保线程2在线程1之前运行
 * 使用 park/un-park 的方式
 */
@Slf4j
public class SequenceTest2 {
    private boolean isThread2 = false;

    public void m1() {
        while (!isThread2) { //如果线程2没有运行过,isThread2标志位就是false,那么线程一进行等待
            LockSupport.park();
        }
        log.info("线程1执行");
    }

    public void m2(Thread thread) {
        isThread2 = true;
        log.info("线程2执行");
        LockSupport.unpark(thread); //给指定线程发通行证
    }

    public static void main(String[] args) {
        SequenceTest2 sequenceTest = new SequenceTest2();
        Thread thread1 = new Thread(sequenceTest::m1, "线程1");
        thread1.start();
        new Thread(() -> {
            sequenceTest.m2(thread1);
        }, "线程2").start();
    }
}